package com.weikuang.fareast.network;


import android.util.Log;

import org.reactivestreams.Subscription;

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作 者：苏昭强
 */
public class AbsPresenter implements Presenter {

    protected final String TAG = getClass().getSimpleName();
    protected final String ERROR_CODE = "1000";
    protected final String SUCCESS_CODE = "0";

    protected ArrayList<Subscription> subscriptionArrayList = new ArrayList<>();

    protected AbsResultView resultView;
    protected CompositeDisposable compositeDisposable;

    public AbsPresenter() {
        if (compositeDisposable == null) compositeDisposable = new CompositeDisposable();
    }

    public void cancelRequest() {
        if (null != subscriptionArrayList) {
            for (Subscription subscription : subscriptionArrayList) {
                if (null != subscription) {
                    subscription.cancel();
                }
            }
        }
        subscriptionArrayList = new ArrayList<>();
    }

    public void addSubscription(Subscription subscription) {
        subscriptionArrayList.add(subscription);
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    protected ObservableTransformer schedulersTransformer() {
        return new ObservableTransformer() {
            @Override
            public ObservableSource apply(Observable upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }


    public <T extends AbsResultView> void attachView(T view) {
        this.resultView = view;
        if (compositeDisposable == null) compositeDisposable = new CompositeDisposable();
    }

    public void detachView() {
        this.resultView = null;
        if (null != compositeDisposable) compositeDisposable.clear();
        compositeDisposable = null;
    }

    public void cancelAccess() {
        if (null != compositeDisposable) compositeDisposable.clear();
    }

    public boolean isViewAttached() {
        return null != resultView;
    }

    @Override
    public void destroy() {
        Log.e(this.getClass().getSimpleName(), "destroy()");
        detachView();
        cancelRequest();
    }

}
